import React, { useState, useEffect, useCallback } from 'react';
import { Button, Table, Modal, Form, Input, notification, Row, Col } from 'antd';
import { fetchApi } from '../../general/api';
import SelectProject from '../project/project_select';
import SelectHost from '../hosts/host_select';
import SelectDynamicType from "../../general/type_select";
import SelectProbeType from "../alert/probe_select"
import AppProbeCreateDrawer from "../app/app_probe_create_drawer"

interface App {
    app_id: number;
    host_id: number;
    project_id: string;
    app_name: string;
    app_now_status_alarm_config: number;
    app_cpu_alarm_config: number;
    app_mem_alarm_config: number;
    app_disk_alarm_config: number;
    app_link_alarm_config: number;
    app_instruction: string;
    app_type: string;
}

const ManageHost: React.FC = () => {
    const [hostList, sethostList] = useState<App[]>([]); // 项目列表
    const [selectedRows, setSelectedRows] = useState<App[]>([]); // 选中行
    const [isEditMode, setIsEditMode] = useState(false); // 编辑模式状态
    const [isModalOpen, setIsModalOpen] = useState(false); // 弹框显示状态
    const [form] = Form.useForm(); // 表单实例
    const [selectedProject, setselectedProject] = useState<string | undefined>(undefined);
    const [selectedHost, setselectedHost] = useState<number | undefined>(undefined);
    // 控制 Drawer 状态
    const [isDrawerOpen, setIsDrawerOpen] = useState(false);
    const [selectedAppName, setSelectedAppName] = useState<string>('');

    // 表格列定义
    const getTableColumns = () => [
        { title: '应用名', dataIndex: 'app_name', key: 'app_name', width: 150 },
        { title: '主机名', dataIndex: 'host_name', key: 'host_name', width: 150 },
        { title: '项目', dataIndex: 'project_name', key: 'project_name', width: 150 },
        { title: '架构', dataIndex: 'host_cpu_architecture', key: 'host_cpu_architecture', width: 150 },
        { title: '主机介绍', dataIndex: 'host_instruction', key: 'host_instruction', width: 150 },
    ].map((col) => ({
        ...col,
        ellipsis: true,
        render: (text: string | React.ReactNode) => (
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block' }}>
                {text}
            </span>
        ),
    }));

    // 获取项目列表数据
    const fetchHostList = useCallback(async () => {
        try {
            const response_data = await fetchApi('/easymonitor/api/app', {
                method: 'GET',
            });
            sethostList(response_data);
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: `获取项目列表失败: ${error}`,
                duration: 2,
            });
        }
    }, []); // 空数组表明 fetchApi 和其他依赖是稳定的

    // 显示通知
    const showNotification = (type: 'success' | 'error' | 'warning', message: string, description: string) => {
        notification[type]({ message, description, duration: 2 });
    };

    // 打开新增/编辑弹框
    const openModal = (record: App | null = null) => {
        setIsModalOpen(true);
        setIsEditMode(!!record);

        setTimeout(() => {
            if (record) {
                form.setFieldsValue({
                    ...record,
                    app_cpu_alarm_config_old: record.app_cpu_alarm_config, // 添加旧值赋值
                    app_mem_alarm_config_old: record.app_mem_alarm_config,
                    app_disk_alarm_config_old: record.app_disk_alarm_config
                });
                setselectedProject(record.project_id);
                setselectedHost(record.host_id);
            } else {
                form.resetFields();
            }
        }, 0); // 确保表单已渲染后再调用
    };

    // 处理项目选择  
    const handleProjectChange = (value: string, label: string) => {
        setselectedProject(value);
        setselectedHost(undefined); // 确保主机下拉框清空
        form.setFieldsValue({ project_id: value, host_id: undefined }); // 确保表单同步更新
    };

    // 处理项目选择  
    const handleHostChange = (value: number, label: string) => {
        setselectedHost(value);
        form.setFieldsValue({ Host_id: value });
    };

    // 关闭弹框
    const closeModal = () => {
        setIsModalOpen(false);
        form.resetFields();
    };

    // 提交表单
    const handleSubmit = async (values: App) => {
        try {
            const method = isEditMode ? 'PUT' : 'POST';
            const endpoint = '/easymonitor/api/app';
            const successMessage = isEditMode ? '项目编辑成功' : '项目新增成功';

            await fetchApi(endpoint, {
                method,
                body: JSON.stringify({ ...values, app_id: isEditMode ? selectedRows[0]?.app_id : undefined }),
            });

            showNotification('success', successMessage, successMessage);
            fetchHostList();
            closeModal();
            setSelectedRows([]);
        } catch (error) {
            showNotification('error', '提交失败', `操作失败: ${error}`);
        }
    };

    // 删除选中的项目
    const handleDelete = async () => {
        if (selectedRows.length === 0) {
            showNotification('warning', '警告', '请选择至少一条记录进行删除！');
            return;
        }

        Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedRows.length} 个项目吗？`,
            onOk: async () => {
                try {
                    await fetchApi('/easymonitor/api/app', {
                        method: 'DELETE',
                        body: JSON.stringify(selectedRows),
                    });

                    showNotification('success', '删除成功', '选中的项目已成功删除。');
                    fetchHostList();
                    setSelectedRows([]);
                } catch (error) {
                    showNotification('error', '删除失败', `删除操作失败: ${error}`);
                }
            },
        });
    };

    const openDrawer = (appName: string) => {
        setSelectedAppName(appName);
        setIsDrawerOpen(true);
    };

    // 初始化加载数据
    useEffect(() => {
        fetchHostList();
    }, [fetchHostList]); // 将 fetchHostList 添加到依赖数组

    return (
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: '700px' }}>
            {/* 按钮区 */}
            <div style={{ marginBottom: '16px', display: 'flex', gap: '8px' }}>
                <Button type="primary" onClick={() => openModal()}>新增</Button>
                <Button
                    onClick={() => {
                        if (selectedRows.length !== 1) {
                            showNotification('warning', '警告', '请选择一条记录进行编辑！');
                        } else {
                            openModal(selectedRows[0]);
                        }
                    }}
                >
                    编辑
                </Button>
                <Button danger onClick={handleDelete}>删除</Button>
            </div>

            {/* 表格区 */}
            <Table
                size="small"
                columns={getTableColumns()}
                dataSource={hostList}
                rowKey="host_id"
                pagination={{ position: ['bottomCenter'], pageSize: 12 }}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: selectedRows.map((row) => row.app_id),
                    onChange: (_, rows) => setSelectedRows(rows),
                }}
                onRow={(record) => ({
                    onClick: () => {
                        const isSelected = selectedRows.some((row) => row.app_id === record.app_id);
                        const updatedRows = isSelected
                            ? selectedRows.filter((row) => row.app_id !== record.app_id)
                            : [...selectedRows, record];
                        setSelectedRows(updatedRows);
                    },
                })}
                style={{ overflowX: 'auto' }}
                locale={{ emptyText: '暂无数据' }}
            />


            {/* 新增/编辑弹框 */}
            <Modal
                title={isEditMode ? '编辑应用' : '新增应用'}
                open={isModalOpen}
                onOk={() => form.submit()}
                onCancel={closeModal}
                destroyOnClose
                footer={[
                    <Button key="drawer" type="default" onClick={() => openDrawer(form.getFieldValue('app_name'))}>
                        新增探针
                    </Button>,
                    <Button key="cancel" onClick={closeModal}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" onClick={() => form.submit()}>
                        提交
                    </Button>,
                ]}
                width="35%"
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                    onFinishFailed={() => showNotification('warning', '表单验证失败', '请填写必填字段！')}
                >
                    <Form.Item name="app_cpu_alarm_config_old" hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item name="app_disk_alarm_config_old" hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item name="app_mem_alarm_config_old" hidden>
                        <Input />
                    </Form.Item>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                label="应用名"
                                name="app_name"
                                rules={[{ required: true, message: '请输入应用名！' }]}>
                                <Input placeholder="请输入应用名" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="项目"
                                name="project_id"
                                rules={[{ required: true, message: '请绑定一个项目' }]}
                            >
                                <SelectProject
                                    style={{ width: '100%' }}
                                    selectedCity={selectedProject}
                                    onCityChange={handleProjectChange} // Using the handleProjectChange function  
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="主机"
                                name="host_id"
                            // rules={[{ required: true, message: '请绑定一个主机' }]}
                            >
                                <SelectHost
                                    projectId={selectedProject}
                                    style={{ width: '100%' }}
                                    selectedCity={selectedHost}
                                    onCityChange={handleHostChange} // Using the handleProjectChange function  
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="应用类型"
                                name="app_type"
                                rules={[{ required: true, message: '请选择一个连接类型！' }]}
                            >
                                <SelectDynamicType
                                    codeType="app_type"
                                    style={{ width: '100%' }}  // 使下拉框宽度自适应
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="状态指标"
                                name="app_now_status_alarm_config"
                            >
                                <SelectProbeType
                                    PorjectID={selectedProject}
                                    HostID={selectedRows[0]?.host_id || 0}
                                    NotBound="1"
                                    style={{ width: '100%' }}  // 使下拉框宽度自适应
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item
                                label="硬盘指标"
                                name="app_disk_alarm_config"
                            >
                                <SelectProbeType
                                    PorjectID={selectedProject}
                                    // HostID={selectedRows[0]?.host_id || 0}
                                    NotBound="1"
                                    style={{ width: '100%' }}  // 使下拉框宽度自适应
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="内存指标"
                                name="app_mem_alarm_config"
                            >
                                <SelectProbeType
                                    PorjectID={selectedProject}
                                    // HostID={selectedRows[0]?.host_id || 0}
                                    NotBound="1"
                                    style={{ width: '100%' }}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="CPU指标"
                                name="app_cpu_alarm_config"
                            >
                                <SelectProbeType
                                    PorjectID={selectedProject}
                                    // HostID={selectedRows[0]?.host_id || 0}
                                    NotBound="1"
                                    style={{ width: '100%' }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Form.Item label="应用介绍" name="host_instruction">
                        <Input.TextArea placeholder="请输入应用介绍" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 侧边抽屉 */}
            <AppProbeCreateDrawer
                isOpen={isDrawerOpen}
                appName={selectedAppName}
                alarm_config_tmp_codes='app_cpu_alarm_config,app_mem_alarm_config,app_disk_alarm_config,app_disk_alarm_config,app_now_status_alarm_config'
                onClose={() => setIsDrawerOpen(false)}
            />
        </div>
    );
};

export default ManageHost;
